
// pages/user/add_work/add_work.js
const innerAudioContext = wx.createInnerAudioContext()
const urls = require('../../../utils/url.js').urls
const http = require('../../../utils/url.js').http
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nc: '',
    tx: '',
    name: '',
    zj: '',
    sj: '',
    fj: '',
    ms: '',
    ypdz: '',
    yynr: '',

    lbArray: [],
    lb: null,
    lbid: null,
    ztArray: [],
    zt: null,
    ztid: null,


    bl: false,
    showView: false,
    windowHeight: 0,
    theplay: false,

    showView2: false,

    starttime: 0,
    endtime: 0,
    time: 0,
    startPoint: null,
    sendLock: false
  },
  userinfo: function (event) {
    wx.navigateTo({
      url: '../../user/user_me/user_me',
    })
  },
  //获取类别下拉
  bindlbChange: function (event) {
    var that = this;
    var index = event.detail.value;
    var lb = that.data.lbArray[index].name;
    var lbid = that.data.lbArray[index].id;
    that.setData({
      lb: lb,
      lbid: lbid
    })
  },
  //获取状态下拉
  bindztChange: function (event) {
    var that = this;
    var index = event.detail.value;
    var zt = that.data.ztArray[index].name;
    var ztid = that.data.ztArray[index].id;
    that.setData({
      zt: zt,
      ztid: ztid
    })
  },
  //查看工单
  ckgd: function (event) {
    wx.navigateTo({
      url: '../../user/work/work',
    })
  },

  //上传工单

  fromSubmit: function (event) {
    // wx.navigateTo({
    //   url: '../../user/work/work',
    // })
    var name = event.detail.value.name;
    var zj = event.detail.value.zj;
    var sj = event.detail.value.sj;
    var fj = event.detail.value.fj;
    var lbid = this.data.lbid;
    var ztid = this.data.ztid;
    var ms = event.detail.value.ms;
    var ypdz = this.data.ypdz;
    var time = this.data.time;
    console.log('音频0' + this.data.ypdz)
    var yynr = this.data.yynr;
    if (name == "" || name == undefined) {
      wx.showToast({
        title: '请输入姓名',
      })
    } else if (zj == "" || zj == undefined) {
      wx.showToast({
        title: '请输入座机号',
      })
    } else if (sj == "" || sj == undefined) {
      wx.showToast({
        title: '请输入手机号',
      })
    } else if (fj == "" || fj == undefined) {
      wx.showToast({
        title: '请输入房间号',
      })
    } else if (lbid == null) {
      wx.showToast({
        title: '请选择维修类别',
      })
    } else if (ztid == null) {
      wx.showToast({
        title: '请选择状态',
      })
    } else {
      console.log('音频1' + ypdz)
      var json = {
        openid: app.globalData.openid,
        sort_id: lbid, //类别id
        state_id: ztid, //状态
        describe: ms, //描述               		
        voice_path: ypdz, //音频地址
        name: name, //姓名     
        phone: sj, //电话
        room: fj, //房间 
        yyzwz: yynr,//语音转文字  
        zjh: zj,
        types: 0,
        yyms: time
      };
      wx.showNavigationBarLoading();
      http(urls.addOrder, json, function (res) {
        console.log(res)
        if (res.code == 0) {
          wx.navigateTo({
            url: '../../user/work/work',
          })
          wx.showToast({
            title: res.msg,
          })
        }
        wx.hideNavigationBarLoading();
      })
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    wx.showNavigationBarLoading();
    var that = this;
    showView: (options.showView == "true" ? true : false)
    showView2: (options.showView == "true" ? true : false)
    var param = {
      openid: app.globalData.openid //openId
    }

    http(urls.details, param, function (res) {
      console.log(res)
      that.setData({
        nc: res.data.nickname,
        tx: res.data.avatarurl,
        name: res.data.realname,
        zj: res.data.zjh,
        sj: res.data.phone,
        fj: res.data.room,
      })
      wx.hideNavigationBarLoading();
    })
    http(urls.sort, null, function (res) {
      console.log(res)
      that.setData({
        lbArray: res.data
      })
      wx.hideNavigationBarLoading();
    })
    http(urls.state, null, function (res) {
      console.log(res)
      that.setData({
        ztArray: res.data
      })
      wx.hideNavigationBarLoading();
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // if (getCurrentPages().length != 0) {
    //   //刷新当前页面的数据
    //   getCurrentPages()[getCurrentPages().length - 1].onLoad()
    // }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  startRecode: function (e) {

    this.data.startPoint = e.touches[0];
    console.log("开始录音");
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    this.setData({
      starttime: timestamp
    })
    console.log("当前时间戳为：" + timestamp);
    const recorderManager = wx.getRecorderManager();
    const options = {
      duration: 10000,
      sampleRate: 16000,
      numberOfChannels: 1, 
      encodeBitRate: 64000,
      format: 'mp3',
      frameSize: 50
    }
    recorderManager.start(options);
    this.data.sendLock = false;//长按时是不上锁的。
    wx.showToast({
      title: "正在录音",
      image:'/image/voice.png',
      duration: 60000//先定义个60秒，后面可以手动调用wx.hideToast()隐藏
    });
  },
  handleTouchMove: function (e) {
    
    var moveLenght = e.touches[e.touches.length - 1].clientY - this.data.startPoint.clientY; //移动距离
    if (Math.abs(moveLenght) > 50) {
      wx.showToast({
        title: "松开手指,取消发送",
        icon: "none",
        duration: 60000
      });
      this.data.sendLock = true;//触发了上滑取消发送，上锁
    } else {
      wx.showToast({
        title: "正在录音，上划取消发送",
        icon: "none",
        duration: 60000
      });
      this.data.sendLock = false;//上划距离不足，依然可以发送，不上锁
    }
  },
  endRecode: function () { //结束录音 
    console.log('结束录音');
    wx.hideToast();//结束录音、隐藏Toast提示框
    var that = this;
    const recorderManager = wx.getRecorderManager();
    // 结束录音时显示语音框
    // showView: (!that.data.showView)
   
    recorderManager.onStop((res) => {
      console.log('。。停止录音。。', res.tempFilePath)
      if (this.data.sendLock) {
        //上锁不发送
        return;
      } else {
        if (res.duration < 1000) {
          wx.showToast({
            title: "录音时间太短",
            icon: "none",
            duration: 1000
          });
          return;
        }
        const {
          tempFilePath
        } = res;
        //结束录音计时  
        clearInterval(that.data.setInter);
        // 储存录音路径用于播放
        wx.setStorageSync('ytempFilePath', tempFilePath)

        that.setData({
          showView: true
        })
        // 获取结束时间
        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        that.setData({
          endtime: timestamp
        })
        console.log('开始时间' + that.data.starttime + "结束时间" + that.data.endtime)
        var time = that.data.endtime - that.data.starttime;
        that.setData({
          time: time
        })

        //上传录音
        wx.uploadFile({
          url: 'http://zsq.free.idcfengye.com/vorder/bdyy', //这是你自己后台的连接
          filePath: tempFilePath,
          name: "yypath", //后台要绑定的名称
          header: {
            "Content-Type": "multipart/form-data"
          },
          //参数绑定
          formData: {
            recordingtime: that.data.recordingTimeqwe,
            topicid: that.data.topicid,
            userid: 1,
            praisepoints: 0
          },
          success: function (res) {

            console.log(res.data);
            var str = JSON.parse(res.data);

            console.log('音频' + str.data.ypdz)
            console.log('音频' + str.data.yynr)
            //  ypdz是存的音频地址
            that.setData({
              ypdz: str.data.ypdz,
              yynr: str.data.yynr
            })
            // console.log('音频' + that.data.ypdz)
            // console.log('音频' + that.data.yynr)
          },
          fail: function (ress) {
            console.log("。。录音保存失败。。");
          }
        })
      }
    })
    recorderManager.stop();


  },
  //播放声音
  play: function () {
    if (this.data.bl == false) {
      this.setData({
        bl: true
      })
    } else {
      this.setData({
        bl: false
      })
    }

    innerAudioContext.onError((res) => {　　　　　　 // 播放音频失败的回调
    })
    innerAudioContext.src = wx.getStorageSync('ytempFilePath'); // 这里可以是录音的临时路径
    if (this.data.bl == true) {

      innerAudioContext.play();
    } else {
      innerAudioContext.stop();
      innerAudioContext.pause();
    }
    innerAudioContext.onEnded(() => {
      this.setData({
        bl: false
      })
    })

  },
  clear: function (event) {

    this.setData({
      ypdz: '',
      showView: false,
      showView2: false
    })

  },
  /**
   * 转换语音文字
   */
  switch: function () {
    this.setData({
      showView2: true
    })

  }

})
